# -*- coding:utf-8 -*-

import os
import json
from core import tomcat
from conf import settings
import urllib,urllib2,sys,os,json,datetime

class ArgvHandler(object):
    def __init__(self,argv_list):
        self.argvs = argv_list
        self.parse_argv()

    def parse_argv(self):
        if len(self.argvs) >1:
            if hasattr(self,self.argvs[1]):
                func = getattr(self,self.argvs[1])
                func()
            else:
                self.help_msg()
        else:
            self.help_msg()

    def help_msg(self):
        msg = '''
        collect_appinfo       get app infomation
        report_appinfo        get and report the app's infomations
        '''
        print(msg)

    def collect_appinfo(self):
        """收集app信息"""
        appinfo = tomcat.appinfo()
        print appinfo
        return appinfo

    def report_appinfo(self):
        appinfo = self.collect_appinfo()
        # print "aaaa",appinfo
        post_url = "service_report"

        data = {"appinfo": json.dumps(appinfo)}
        print "submit----",data
        response = self.__submit_appinfo(post_url,data,method="post")
        # print response

    def __submit_appinfo(self,action_type,data,method):

        if action_type in settings.Params['urls']:
            if type(settings.Params['port']) is int:
                url = "http://%s:%s%s" %(settings.Params['server'],settings.Params['port'],settings.Params['urls'][action_type])
            else:
                url = "http://%s%s" %(settings.Params['server'],settings.Params['urls'][action_type])

            print('Connecting [%s], it may take a minute' % url)
            if method == "get":
                args = ""
                for k,v in data.items():
                    args += "&%s=%s" %(k,v)
                args = args[1:]
                url_with_args = "%s?%s" %(url,args)
                try:
                    req = urllib2.Request(url_with_args)
                    req_data = urllib2.urlopen(req,timeout=settings.Params['request_timeout'])
                    callback = req_data.read()
                    print("-->server response:",callback)
                    return callback
                except urllib2.URLError as e:
                    sys.exit("\033[31;1m%s\033[0m"%e)
            elif method == "post":
                # print "ddddd",data
                try:
                    data_encode = urllib.urlencode(data)
                    req = urllib2.Request(url=url,data=data_encode)
                    res_data = urllib2.urlopen(req,timeout=settings.Params['request_timeout'])
                    callback = res_data.read()
                    callback = json.loads(callback)
                    print("\033[31;1m[%s]:[%s]\033[0m response:\n%s" %(method,url,callback))
                    return callback
                except Exception as e:
                    sys.exit("\033[31;1m%s\033[0m"%e)
        else:
            raise KeyError
